package mspbots.timedoctor.client.oauth;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * com.mspbots.doctor.core.RedirectAuthController
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/3/19
 */
@Log4j2
@Controller
@RequestMapping("oauth")
@RequiredArgsConstructor
public class AuthController {

    private final V1AuthService v1AuthService;
    private final V2AuthService v2AuthService;

    @GetMapping("redirect")
    public Mono<String> redirect(@RequestParam Map<String, Object> params, Model model) {
        log.debug("Oauth2.0 redirect call params {}", params);
        Assert.notNull(params.get("tenantId"), () -> "Login params [tenantId] not null. ");
        Assert.notNull(params.get("code"), () -> "Login params [code] not null. ");
        model.addAllAttributes(params);
        return this.v1AuthService.authToken(params)
                .map(authorizationCode -> model.addAttribute("token", authorizationCode))
                .map(val -> "redirect");
    }

    @ResponseBody
    @GetMapping("token")
    public Mono<String> getToken(@RequestParam Long tenantId) {
        log.debug("Refresh Token params tenantId is {}", tenantId);
        return this.v1AuthService.getToken(tenantId);
    }


    @ResponseBody
    @PostMapping("v2/login")
    public Mono<String> v2Login(@RequestBody Map<String, Object> params) {
        Assert.notNull(params.get("tenantId"), () -> "Login params [tenantId] not null. ");
        Assert.notNull(params.get("email"), () -> "Login params [email] not null. ");
        Assert.notNull(params.get("password"), () -> "Login params [password] not null. ");
        return this.v2AuthService.authToken(params);
    }
}
